package tech.yangzhijie.basic.knowledge.mianshi;

import java.util.concurrent.*;

public class Test14DeadLock {

    public static void main(String[] args) {
        ExecutorService executorService = new ThreadPoolExecutor(2, 4, 2, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(2), Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
        DeadLockResource01 deadLockResource01 = new DeadLockResource01("AA");
        DeadLockResource02 deadLockResource02 = new DeadLockResource02("BB");
        try {
            executorService.execute(()->{
                synchronized (deadLockResource01){
                    try {
                        TimeUnit.SECONDS.sleep(2);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("获取锁 " + deadLockResource01.getName());
                    synchronized (deadLockResource02){
                        System.out.println("获取锁 " + deadLockResource02.getName());
                    }
                }
            });

            executorService.execute(()->{
                synchronized (deadLockResource02){
                    System.out.println("获取锁 " + deadLockResource02.getName());
                    synchronized (deadLockResource01){
                        System.out.println("获取锁 " + deadLockResource01.getName());
                    }
                }
            });
        }finally {
            executorService.shutdown();
        }
    }
}

class DeadLockResource01 {
    private String name;

    public String getName() {
        return name;
    }

    public DeadLockResource01(String name) {
        this.name = name;
    }
}

class DeadLockResource02 {
    private String name;

    public DeadLockResource02(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}
